import java.util.*;

public class BinaryTreeZigzagLevelOrderTraversal {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isOrderLeft = true;

        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while(size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);

                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            if(isOrderLeft) {
                // 为 true, 按正常顺序添加
                ret.add(list);
            }else {
                // 如果是 false, 翻转之后再添加
                Collections.reverse(list);
                ret.add(list);
            }
            isOrderLeft = !isOrderLeft;
        }
        return ret;
    }
}
